package com.etoak.common.jwt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.time.DateUtils;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class MyJwtUtil {

    public static final String STRING_KEY = "11111111111111111111111111111111";

    /**
     * 签名key
     */
    public static final Key KEY = Keys.hmacShaKeyFor(STRING_KEY.getBytes());

    /**
     * 创建JWT -Json Web Token
     * @param claims
     * @return
     */
    public static String create(Map<String, Object> claims) {
        Date now = new Date();
        return Jwts.builder()
                .signWith(KEY)
                .setClaims(claims)
                .setIssuedAt(new Date()) //JWT 签发时间
                .setExpiration(DateUtils.addHours(now,12)) //过期时间
                .compact();
    }

    /**
     * 解析JWT
     * @param token
     * @return
     */
    public static Map<String, Object> parse(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
